<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>支付宝即时到账批量退款有密接口接口</title>
</head>
<?php
/* *
 * 功能：即时到账批量退款有密接口接入页
 * 版本：3.3
 * 修改日期：2012-07-23
 * 说明：
 * 以下代码只是为了方便商户测试而提供的样例代码，商户可以根据自己网站的需要，按照技术文档编写,并非一定要使用该代码。
 * 该代码仅供学习和研究支付宝接口使用，只是提供一个参考。

 *************************注意*************************
 * 如果您在接口集成过程中遇到问题，可以按照下面的途径来解决
 * 1、商户服务中心（https://b.alipay.com/support/helperApply.htm?action=consultationApply），提交申请集成协助，我们会有专业的技术工程师主动联系您协助解决
 * 2、商户帮助中心（http://help.alipay.com/support/232511-16307/0-16307.htm?sh=Y&info_type=9）
 * 3、支付宝论坛（http://club.alipay.com/read-htm-tid-8681712.html）
 * 如果不想使用扩展功能请把扩展功能参数赋空值。
 */

//TODO::根据不同商家选择相应的支付宝配置文件
$order_from = intval($_POST['from']);
switch($order_from) {
    case 1:
        //云顶
        $notify_url = "http://www.12301.cc/alipay/ali_refund/notify_url_yd.php";
        $config_path  = "/var/www/html/new/d/yd/alipay/alipay.cfg.php";
        $seller_email = '3099889658@qq.com';
        break;
    case 2:
        //预留鼓浪屿
        $notify_url = "http://www.12301.cc/alipay/ali_refund/notify_url_gly.php";
        $config_path  = "/var/www/html/alipay/alipay.config.gly.php";
        $seller_email = 'ylq@gly.cn';
        break;
    default:
        //票付通
        $notify_url = "http://www.12301.cc/alipay/ali_refund/notify_url.php";
        $config_path  = "/var/www/html/alipay/alipay.config.php";
        $seller_email = 'pft12301@126.com';//卖家支付宝帐户
        break;
}
include($config_path);
include("/var/www/html/alipay/lib/alipay_notify.class.php");
include("/var/www/html/alipay/lib/alipay_submit.class.php");
include("/var/www/html/new/com.inc.php");
include("/var/www/html/new/d/class/SoapInit.class.php");

/**
 * 计算订单取消费用
 *
 * @param $tid 门票ID，数组或数字
 * @param $begintime  订单游玩时间
 * @return array|bool|int
 */
function count_cost_fee($tid_price, $begintime)
{
    $tid        = array_keys($tid_price);
    $price_arr  = array_values($tid_price);
    $limit      = count($tid);
    if ($limit==1) {
        $where = "=" . $tid[0];
    }
    elseif($limit>1) {
        $where = 'IN(' . implode(',', $tid) . ')';
    }
    else {
        return false;
    }

    $play_date = strtotime( $begintime . ' 00:00:00');
    $today     = strtotime(date('Y-m-d 00:00:00'));
    $day_diff  = ($play_date - $today) / 86400;//距离游玩时间的天数
    //取消费用,cancel_cost,reb=>手续费,reb_type=>手续费类型0%，1固定金额

    //使用cancel_cost字段收取手续费的供应商，目前（2014年12月19日）只有云顶
    $use_cancel_cost = array(
        7133,7134,7135,7136,
    );
    //reb_type
    $sql = "SELECT id,cancel_cost,reb,apply_did FROM uu_jq_ticket WHERE id $where LIMIT $limit";
    $GLOBALS['le']->query($sql);
    $fee_cost = array();
//    $use_cancel_cost_flag = false;
    $total_fee = 0;//取消费用，考虑到后期有可能订单里面的票取消费用计算方式不一致
    while($row = $GLOBALS['le']->fetch_assoc()) {
        if (in_array($row['apply_did'], $use_cancel_cost)) {
            if (!$row['cancel_cost']) continue;
            $fee_cost[$row['id']] = $row['cancel_cost'];
        }
        elseif ($row['reb']>0) {
            if ($row['reb_type']==1) {
                $total_fee += $row['reb'];
            }
            else {
                $total_fee += ($row['reb'] * $tid_price[$row['id']]) / 100;
            }
        }
    }
    if (count($fee_cost)) {
        foreach ($fee_cost as $tid=>$cancel_cost) {
            //取消费用一维数组 array('提前天数'=>'百分比')
            $cancel_cost_arr = json_encode($cancel_cost, true);
            $day_arr         = array_keys($cancel_cost_arr);
            sort($day_arr);
            $min_day         = min($day_arr);
            $max_day         = max($day_arr);
            if ($day_diff <= $min_day) {
                $fee = $cancel_cost_arr[$min_day];
            }
            elseif ($day_diff >= $max_day) {
                $fee = 0;
            } else {
                foreach ($day_arr as $key=>$val) {
                    if ($day_diff >= $val && $day_diff <= $day_arr[$key+1]) {
                        $fee = $day_arr[$key+1];
                        break;
                    }
                }
            }
            $total_fee += ($fee *$price_arr[$tid]) / 100 ;
        }
    }
    return $total_fee;
}
/**************************请求参数**************************/

//处理订单数据BEGIN
if (empty($_POST['ordernum'])) {
    exit('订单号为空');
}
$ordernum = trim($_POST['ordernum']);//13
$soap = SoapInit::GetSoapInside();
$xml  = $soap->Order_Globle_Search("", "", "", "", "", "", "", "", "", "", "", "",
    $ordernum, "", "", "", "", "", "", "1", "0", "100", "0", "0",
    "", "0", "", "0", "", "", "", "0", "0");
//echo $xml;exit;
$order_arr = simplexml_load_string($xml);
//print_r($order_arr);exit;
if (!count($order_arr)) {
    exit("订单不存在。");
}
//echo $order_arr->Rec->UUstatus;
//echo $order_arr->Rec->UUpaystatus;
//echo $order_arr->Rec->UUpmode;
//exit;
//TODO::判断订单状态，未使用，已支付
if ($order_arr->Rec->UUstatus!=0 && $order_arr->Rec->UUpaystatus!=1
    && $order_arr->Rec->UUpmode !=1 ) {
    exit("只有已支付未使用并且是使用支付宝支付的订单方可退款。");
}
$order_type = 0;
//TODO::判断订单类型
if ($order_arr->Rec->UUpack_order==1) {
    //套票
    $order_type = 1;
}
elseif ($order_arr->Rec->UUconcat_id>0) {
    //联票
    $order_type = 2;
}
else {
    //普通订单
}
//退款当天日期，必填，格式：年[4位]-月[2位]-日[2位] 小时[2位 24小时制]:分[2位]:秒[2位]，如：2007-10-01 13:13:13
$refund_date = date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']);
//批次号，我们固定13位，必填，格式：当天日期[8位]+序列号[3至24位]，如：201008010000001
$batch_no = date('Ymd', $_SERVER['REQUEST_TIME']).mt_rand(10000,99999);

//退款笔数
$batch_num = 1;
//退票数，0表示取消订单
$tnum      = intval($_POST['num']);
$fee_cost  = 0;//取消费用
//取消订单
if ($tnum == 0 ) {
    if ($order_type==2) {
        $xml_child  = $soap->Order_Globle_Search("", "", "", "", "", "", "", "", "", "", "", "",
            $ordernum, "", "", "", "", "", "", "1", "0", "100", "0", "0",
            "", "0", "", "0", "", "", "1", "0", "0");
        $child_order = simplexml_load_string($xml_child);
        foreach ($child_order as $order) {
            if ($order->UUordernum==$ordernum) continue;
            $tid_price[(int)$order->UUtid] = (int)$order->UUtprice;
        }
        $fee_cost = count_cost_fee($tid_price,  (string)$order_arr->Rec->UUbegintime);
    }
    else {
        $fee_cost = count_cost_fee(
            array( (int)$order_arr->Rec->UUtid => (int)$order_arr->Rec->UUtotalmoney),
            (string)$order_arr->UUbegintime
        );
    }
    $total_fee = $order->Rec->UUtotalmoney - $fee_cost;//该笔支付订单总金额-取消费用
    $subject   = '取消订单退款';
}
elseif ($tnum>1 && $tnum < $order_arr->UUtnum) {
    //修改票数，退款金额=下单时的价格 * 票数
    $total_fee = $order_arr->Rec->UUtprice * $tnum;
    $subject   = '修改订单退款';
}
else {
    exit ("修改票数不能超过下单时的票数");
}
//考虑联票订单
//处理订单数据END

$sql  = <<<SQL
INSERT INTO pft_order_refund(ordernum,refund_num,refund_money,refund_time,batch_no)
 VALUES($ordernum, $tnum, $total_fee, '$refund_date', '$batch_no')
SQL;
$GLOBALS['le']->query($sql);

//TODO::获取交易号
$sql = "SELECT trade_no FROM pft_alipay_rec WHERE out_trade_no='$ordernum' LIMIT 1";
$GLOBALS['le']->query($sql);
$GLOBALS['le']->fetch_assoc();
$trade_no = $GLOBALS['le']->f('trade_no');

//服务器异步通知页面路径

//必填，参数detail_data的值中，“#”字符出现的数量加1，最大支持1000笔（即“#”字符出现的数量999个）
//退款详细数据
//$detail_data = $_POST['WIDdetail_data'];
$detail_data = $trade_no.'^'.$total_fee.'^'.$subject;
 //必填，具体格式请参见接口技术文档
/************************************************************/
//构造要请求的参数数组，无需改动
$parameter = array(
		"service"       => "refund_fastpay_by_platform_pwd",
		"partner"       => trim($alipay_config['partner']),
		"notify_url"    => $notify_url,
		"seller_email"  => $seller_email,
		"refund_date"   => $refund_date,
		"batch_no"      => $batch_no,
		"batch_num"     => $batch_num,
		"detail_data"   => $detail_data,
		"_input_charset"=> trim(strtolower($alipay_config['input_charset']))
);

//建立请求
$alipaySubmit = new AlipaySubmit($alipay_config);
//$res  = $alipaySubmit->buildRequestHttp($parameter);
//var_dump($res);
$html_text = $alipaySubmit->buildRequestForm($parameter,"get", "确认");
echo $html_text;

?>
</body>
</html>